package com.iyundao.io.Service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iyundao.io.Service.PartymemberService;
import com.iyundao.io.mapper.*;
import com.iyundao.io.model.*;
import com.iyundao.io.tools.MD5Util;
import com.iyundao.io.tools.PartyMemberShow;
import com.iyundao.io.tools.PartymemberVo;
import com.iyundao.io.tools.ResponseData;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PartymemberServiceImpl implements PartymemberService {

    @Autowired
    private PartyMemberMapper partyMemberMapper;

    @Autowired
    private PartyMemberOrganizationMapper partyMemberOrganizationMapper;

    @Autowired
    private PartyMemberCustomMapper memberCustomMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private UserDeptMapper userDeptMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserCustomMapper userCustomMapper;

    @Autowired
    private IntegralMapper integralMapper;

    @Autowired
    private SysDeptCustomMapper sysDeptCustomMapper;


    /**
     * 人员添加的批量操作
     *
     * @param list 人员信息
     * @return
     */
    @Override
    public ResponseData batchInsert(List<PartymemberVo> list) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (list.equals("") || list == null) {
            return new ResponseData(0, "传入数据，详细信息或组织id为空");
        } else {
            List<Map<String, String>> list1 = new ArrayList<>();
            List<Map<String, String>> list2 = new ArrayList<>();
            for (PartymemberVo pVo : list) {
                try {
                    //判断手机号是否存在
                    int i1 = memberCustomMapper.selectByPhone(pVo.getPartymemberphone());
                    if (i1 == 0) {
                        /**
                         * 党员表信息添加
                         */
                        PartyMember partyMember = new PartyMember();
                        partyMember.setPartymemberaddress(pVo.getPartymemberaddress());
                        partyMember.setPartymemberbirthday(simpleDateFormat.parse(pVo.getPartymemberbirthday()));
                        partyMember.setPartymemberjointime(simpleDateFormat.parse(pVo.getPartymemberjointime()));
                        partyMember.setPartymembername(pVo.getPartymembername());
                        partyMember.setPartymemberphone(pVo.getPartymemberphone());
                        partyMember.setPartymembersex(pVo.getPartymembersex());
                        int i = partyMemberMapper.insert(partyMember);
                        if (i > 0) {

                            /**
                             * 添加积分信息
                             */
                            PartyMember partyMember2 = memberCustomMapper.selectAllByPhone(partyMember.getPartymemberphone());
                            Integral integral = new Integral();
                            integral.setPartymemberid(partyMember2.getId());
                            integral.setIntegralsum(0);
                            integral.setIntegralnow(0);
                            integralMapper.insertSelective(integral);



                            /**
                             * 查询组织
                             */
                            SysDeptProvider sysDept = sysDeptCustomMapper.selectByRealName(pVo.getName());

                            /**
                             * 添加党员组织关系
                             */
                            PartyMemberOrganization partyMemberOrganization = new PartyMemberOrganization();
                            Integer id = partyMemberMapper.selectByPhone(pVo.getPartymemberphone()).getId();
                            //partyMemberOrganization.setJointime(simpleDateFormat.parse(pVo.getJointime()));
                            partyMemberOrganization.setOrganizationid(sysDept.getSid());
                            partyMemberOrganization.setPartymemberid(id);
                            int insert = partyMemberOrganizationMapper.insert(partyMemberOrganization);
                            if (insert > 0) {
                                String sid = UUID.randomUUID().toString();
                                Date date = new Date();

                                /**
                                 * 添加用户表
                                 */
                                SysUser sysUser = new SysUser();
                                sysUser.setLoginName(pVo.getPartymemberphone());
                                sysUser.setShowName(pVo.getPartymembername());
                                sysUser.setRealName(pVo.getPartymembername());
                                sysUser.setLoginPwd(MD5Util.encrypt(pVo.getPartymemberphone()));
                                sysUser.setPhone(pVo.getPartymemberphone());
                                sysUser.setBirthday(simpleDateFormat.parse(pVo.getPartymemberbirthday()));
                                sysUser.setSex(pVo.getPartymembersex());
                                sysUser.setAddress(pVo.getPartymemberaddress());
                                sysUser.setCreateDate(date);
                                sysUser.setSid(sid);
                                sysUser.setCreateId(sid);
                                sysUser.setFlag("1");

                                int i2 = sysUserMapper.insertSelective(sysUser);
                                if (i2 > 0) {
                                    /**
                                     * 添加用户与组织的关系
                                     */
                                    UserDept userDept = new UserDept();
                                    userDept.setUid(sid);
                                    userDept.setDid(sysDept.getSid());
                                    userDeptMapper.insert(userDept);

                                    /**
                                     * 添加用户与角色的关系
                                     */
                                    UserRole userRole = new UserRole();
                                    userRole.setSid(UUID.randomUUID().toString());
                                    userRole.setUid(sid);
                                    userRole.setRid(pVo.getRoleSid());
                                    userRoleMapper.insert(userRole);

                                    Map<String, String> map = new HashMap<>();
                                    map.put("name", pVo.getPartymembername());
                                    map.put("message", "人员添加成功");
                                    map.put("phone",pVo.getPartymemberphone());
                                    map.put("name",pVo.getName());
                                    list2.add(map);
                                } else {
                                    Map<String, String> map = new HashMap<>();
                                    map.put("name", pVo.getPartymembername());
                                    map.put("message", "人员添加添加成功，组织绑定成功，用户添加失败");
                                    map.put("phone",pVo.getPartymemberphone());
                                    map.put("name",pVo.getName());
                                    list1.add(map);
                                }

                            } else {
                                Map<String, String> map = new HashMap<>();
                                map.put("name", pVo.getPartymembername());
                                map.put("message", "人员添加添加成功，组织绑定失败");
                                map.put("phone",pVo.getPartymemberphone());
                                map.put("name",pVo.getName());
                                list1.add(map);
                            }
                        } else {
                            Map<String, String> map = new HashMap<>();
                            map.put("name", pVo.getPartymembername());
                            map.put("message", "人员添加失败");
                            map.put("phone",pVo.getPartymemberphone());
                            map.put("name",pVo.getName());
                            list1.add(map);
                        }
                    } else {
                        Map<String, String> map = new HashMap<>();
                        map.put("name", pVo.getPartymembername());
                        map.put("message", "手机号已存在");
                        map.put("phone",pVo.getPartymemberphone());
                        map.put("name",pVo.getName());
                        list1.add(map);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Map<String, String> map = new HashMap<>();
                    map.put("name", pVo.getPartymembername());
                    map.put("message", e.getMessage());
                    map.put("phone",pVo.getPartymemberphone());
                    map.put("name",pVo.getName());
                    list1.add(map);
                }
            }
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("success", list2);
            hashMap.put("error", list1);
            return new ResponseData(200, "信息", hashMap);

        }
    }

    @Override
    public ResponseData insert(PartyMemberShow partymemberVo) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //人员信息添加
        PartyMember partyMember = new PartyMember();
        partyMember.setPartymemberaddress(partymemberVo.getPartymemberaddress());
        try {
            partyMember.setPartymemberbirthday(simpleDateFormat.parse(partymemberVo.getPartymemberbirthday()));
            partyMember.setPartymemberjointime(simpleDateFormat.parse(partymemberVo.getPartymemberjointime()));
            partyMember.setPartymembername(partymemberVo.getPartymembername());
            partyMember.setPartymemberphone(partymemberVo.getPartymemberphone());
            partyMember.setPartymembersex(partymemberVo.getPartymembersex());

            PartyMember partyMember1 = null;
            partyMember1 = partyMemberMapper.selectByPhone(partymemberVo.getPartymemberphone());

            if (partyMember1 == null || partyMember1.equals("")) {
                int i = partyMemberMapper.insert(partyMember);
                if (i > 0) {

                    /**
                     * 添加积分信息
                     */
                    PartyMember partyMember2 = memberCustomMapper.selectAllByPhone(partyMember.getPartymemberphone());
                    Integral integral = new Integral();
                    integral.setPartymemberid(partyMember2.getId());
                    integral.setIntegralsum(0);
                    integral.setIntegralnow(0);
                    integralMapper.insertSelective(integral);

                    /**
                     * 人员添加成功后，添加人员组织关系
                     */
                    PartyMemberOrganization partyMemberOrganization = new PartyMemberOrganization();
                    Integer id = partyMemberMapper.selectByPhone(partymemberVo.getPartymemberphone()).getId();
                    //partyMemberOrganization.setJointime(simpleDateFormat.parse(partymemberVo.getJointime()));
                    partyMemberOrganization.setOrganizationid(partymemberVo.getOrganizationid());
                    partyMemberOrganization.setPartymemberid(id);
                    Integer i1 = partyMemberOrganizationMapper.insert(partyMemberOrganization);
                    if (i1 > 0) {
                        String sid = UUID.randomUUID().toString();
                        Date date = new Date();

                        //添加用户表
                        SysUser sysUser = new SysUser();
                        sysUser.setLoginName(partymemberVo.getPartymemberphone());
                        sysUser.setShowName(partymemberVo.getPartymembername());
                        sysUser.setRealName(partymemberVo.getPartymembername());
                        sysUser.setLoginPwd(MD5Util.encrypt(partymemberVo.getPartymemberphone()));
                        sysUser.setPhone(partymemberVo.getPartymemberphone());
                        sysUser.setBirthday(simpleDateFormat.parse(partymemberVo.getPartymemberbirthday()));
                        sysUser.setSex(partymemberVo.getPartymembersex());
                        sysUser.setAddress(partymemberVo.getPartymemberaddress());
                        sysUser.setCreateDate(date);
                        sysUser.setSid(sid);
                        sysUser.setCreateId(sid);
                        sysUser.setFlag("1");

                        int i2 = sysUserMapper.insertSelective(sysUser);
                        if (i2 > 0) {

                            //添加用户表与组织关系
                            UserDept userDept = new UserDept();
                            userDept.setUid(sid);
                            userDept.setDid(partymemberVo.getOrganizationid());
                            userDeptMapper.insert(userDept);

                            //添加用户与角色关系
                            UserRole userRole = new UserRole();
                            userRole.setSid(UUID.randomUUID().toString());
                            userRole.setUid(sid);
                            userRole.setRid(partymemberVo.getRoleSid());
                            userRoleMapper.insert(userRole);

                            return new ResponseData(200, "成功");
                        } else {
                            return new ResponseData(0, "人员添加添加成功，组织绑定成功，用户添加失败");
                        }

                    } else {
                        return new ResponseData(0, "人员添加添加成功，组织绑定失败");
                    }
                } else {
                    return new ResponseData(0, "人员添加失败");
                }
            } else {
                return new ResponseData(0, "添加失败，手机号已存在");
            }


        } catch (ParseException e) {
            e.printStackTrace();
            return new ResponseData(0, e.getMessage());
        }
    }

    /**
     * 转出操作
     * @param id  人员id
     * @return
     */
    @Override
    public ResponseData rollOut(Integer id) {
        PartyMember partyMember = partyMemberMapper.selectById(id);
        SysUser sysUser = userCustomMapper.selectByPhone(partyMember.getPartymemberphone());
        Date date = new Date();
        memberCustomMapper.rollOut(date,id);

        PartyMemberOrganization partyMemberOrganization = new PartyMemberOrganization();
        partyMemberOrganization.setOrganizationid("0");
        partyMemberOrganization.setPartymemberid(id);
        partyMemberOrganization.setJointime(date);
        partyMemberOrganizationMapper.insertSelective(partyMemberOrganization);

        userCustomMapper.deleteUserDept(sysUser.getSid());
        userCustomMapper.deleteUserRole(sysUser.getSid());
        return new ResponseData(200,"操作成功");
    }

    /**
     * 加入组织
     * @param id
     * @return
     */
    @Override
    public ResponseData rollJoin(Integer id,String organzationid, String roleId) {
        PartyMember partyMember = partyMemberMapper.selectById(id);
        SysUser sysUser = userCustomMapper.selectByPhone(partyMember.getPartymemberphone());
        Date date = new Date();
        memberCustomMapper.rollOut(date,id);

        PartyMemberOrganization partyMemberOrganization = new PartyMemberOrganization();
        partyMemberOrganization.setOrganizationid(organzationid);
        partyMemberOrganization.setPartymemberid(id);
        partyMemberOrganization.setJointime(date);
        partyMemberOrganizationMapper.insertSelective(partyMemberOrganization);

        UserDept userDept = new UserDept();
        userDept.setDid(organzationid);
        userDept.setUid(sysUser.getSid());
        userDeptMapper.insert(userDept);

        UserRole userRole = new UserRole();
        userRole.setSid(UUID.randomUUID().toString());
        userRole.setUid(sysUser.getSid());
        userRole.setRid(roleId);
        userRoleMapper.insert(userRole);

        return new ResponseData(200,"操作成功");
    }

    @Override
    public ResponseData selectById(Integer id) {
        PartyMember partyMember = partyMemberMapper.selectById(id);
        return new ResponseData(200, "成功", partyMember);
    }

    /**
     * 修改党员信息
     *
     * @param partyMember
     * @return
     */
    @Override
    public ResponseData updatePartymember(PartyMemberShow partyMember) {
        if (partyMember.equals("") || partyMember == null) {
            return new ResponseData(0, "传入参数为空");
        } else {
            try {
                PartyMember partyMember1 = partyMemberMapper.selectById(partyMember.getId());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

                //党员表修改
                PartyMember partyMember2 = new PartyMember();
                partyMember2.setId(partyMember.getId());
                partyMember2.setPartymemberaddress(partyMember.getPartymemberaddress());
                partyMember2.setPartymemberphone(partyMember.getPartymemberphone());

                partyMember2.setPartymemberjointime(simpleDateFormat.parse(partyMember.getPartymemberjointime()));
                partyMember2.setPartymemberbirthday(simpleDateFormat.parse(partyMember.getPartymemberbirthday()));
                partyMember2.setPartymembersex(partyMember.getPartymembersex());
                partyMember2.setPartymembername(partyMember.getPartymembername());
                partyMemberMapper.updatePartymember(partyMember2);

                //用户表修改
                SysUser sysUser = userCustomMapper.selectByPhone(partyMember1.getPartymemberphone());
                sysUser.setPhone(partyMember.getPartymemberphone());
                sysUser.setRealName(partyMember.getPartymembername());
                sysUser.setShowName(partyMember.getPartymembername());
                sysUser.setLoginPwd(MD5Util.encrypt(partyMember.getPartymemberphone()));
                sysUser.setSex(partyMember.getPartymembersex());
                sysUser.setAddress(partyMember.getPartymemberaddress());
                sysUser.setBirthday(simpleDateFormat.parse(partyMember.getPartymemberbirthday()));
                sysUser.setLoginName(partyMember.getPartymemberphone());
                sysUserMapper.updateByPrimaryKeySelective(sysUser);

                //修改角色
                UserRole userRole = new UserRole();
                userRole.setUid(sysUser.getSid());
                userRole.setRid(partyMember.getRoleSid());
                userRoleMapper.updateByUid(userRole);

                return new ResponseData(200, "修改成功");
            } catch (ParseException e) {
                e.printStackTrace();
                return new ResponseData(0,e.getMessage());
            }
        }
    }

    /**
     * 根据组织id查询人员
     *
     * @return
     */
    @Override
    public ResponseData selectByOrganizationId(SysUserProvider sysUser) {
        String sid = sysUser.getSysDept().getSid();
        List<PartymemberVo> list = memberCustomMapper.selectByOrganizationId(sid);
        Map<String, java.lang.Object> map = new HashMap<>();
        map.put("user", sysUser);
        map.put("info", list);
        return new ResponseData(200, "成功", map);
    }

    @Override
    public ResponseData selectByOrganizationIdNoManager(SysUserProvider sysUser) {
        String sid = sysUser.getSysDept().getSid();
        List<PartymemberVo> list = memberCustomMapper.selectByOrganizationIdNoManager(sid);
        Map<String, java.lang.Object> map = new HashMap<>();
        map.put("user", sysUser);
        map.put("info", list);
        return new ResponseData(200, "成功", map);
    }

    @Override
    public ResponseData selectByCondition(PartymemberCondition partymemberCondition) {
        if (partymemberCondition.toString().equals("") || partymemberCondition.toString() == null) {
            return new ResponseData(0, "传入数据为空");
        } else {
            String sid = partymemberCondition.getId();
            if (partymemberCondition.getAge() != null && !partymemberCondition.getAge().equals("")) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                String format1 = format.format(date);
                String year = String.valueOf(Integer.valueOf(format1) - Integer.valueOf(partymemberCondition.getAge()));
                String date1 = year + "-01-01";
                String date2 = year + "-12-31";
                List<PartymemberVo> list = memberCustomMapper.selectByAge(date1, date2, sid);
                return new ResponseData(200, "成功", list);
            }

            if (!partymemberCondition.getName().equals("") && partymemberCondition.getName() != null) {
                String s = "%" + partymemberCondition.getName() + "%";
                partymemberCondition.setName(s);
                List<PartymemberVo> list = memberCustomMapper.selectByLikeName(partymemberCondition.getName(), sid);
                return new ResponseData(200, "成功", list);
            }

            if (!partymemberCondition.getJointime().equals("") && partymemberCondition.getJointime() != null) {
                String jointime = partymemberCondition.getJointime();
                String date1 = jointime + "-01-01";
                String date2 = jointime + "-12-31";
                List<PartymemberVo> list = memberCustomMapper.selectByJoinTime(date1, date2, sid);
                return new ResponseData(200, "成功", list);
            }
            return new ResponseData(0, "没有匹配查询条件");

        }
    }

    @Override
    public ResponseData selectBySid(Integer pagenum, Integer pageSize, String sid) {
        PageHelper.startPage(pagenum, pageSize);
        List<PartymemberVo> list = memberCustomMapper.selectBySid(sid);
        PageInfo<PartymemberVo> pageInfo = new PageInfo<>(list);
        return new ResponseData(200, "成功", pageInfo);
    }

    @Override
    public ResponseData selectBySid(String sid) {
        List<PartymemberVo> list = memberCustomMapper.selectBySid(sid);
        return new ResponseData(200, "成功", list);
    }

    /**
     * 查询未加入组织人员
     * @return
     */
    @Override
    public ResponseData selectNoJoin() {
        return new ResponseData(200,"成功",memberCustomMapper.selectNoJoinDept());
    }

    /**
     * 通过名字查询未加入组织人员
     * @return
     */
    @Override
    public ResponseData selectNoJoinByName(String name) {
        String s = "%" + name + "%";
        return new ResponseData(200,"成功",memberCustomMapper.selectNoJoinDeptByName(s));
    }
}
